﻿using System.Linq;
using System.Web.Mvc;
using System.Web.Routing;
using ResourcesOverMvc.Web.Mvc;
using Samples.BareMinimum.Areas.Services.Models;

namespace Samples.BareMinimum.Areas.Services.Controllers
{
    [MultipleRepresentations]
    public class ProductsController : Controller
    {
        [HttpGet]
        public ActionResult Index()
        {
            var products = Product.AllProducts;

            foreach (var product in products)
            {
                product.Uri = Url.Action("Details", "Products", new RouteValueDictionary { { "Id", product.Id }, { "Area", "Services" } }, Request.Url.Scheme, string.Empty);
            }

            return View(Product.AllProducts);
        }

        [HttpPost]
        public ActionResult Index([MultipleRepresentationsBinder] Product newProduct)
        {
            newProduct.Id = Product.AllProducts.Max(p => p.Id) + 1;
            newProduct.Uri = Url.Action("Details", "Products", new RouteValueDictionary { { "Id", newProduct.Id }, { "Area", "Services" } }, Request.Url.Scheme, string.Empty);
            Product.AllProducts.Add(newProduct);
            return View("Details", newProduct);
        }

        [HttpGet]
        public ActionResult Details(int id)
        {
            return View(Product.AllProducts.First(p => p.Id == id));
        }

        [HttpPut]
        public ActionResult Details(int id, [MultipleRepresentationsBinder] Product newVersionOfProduct)
        {
            Product.AllProducts.Remove(id);
            newVersionOfProduct.Id = id;
            Product.AllProducts.Add(newVersionOfProduct);
            newVersionOfProduct.Uri = Url.Action("Details", "Products", new RouteValueDictionary { { "Id", newVersionOfProduct.Id }, { "Area", "Services" } }, Request.Url.Scheme, string.Empty);
            return View("Details", newVersionOfProduct);
        }
    }
}
